為了讓類別可以擁有多個constructor,dart提供了named constructors,我們可以命名constructors
class Point {
double x, y;
Point(this.x, this.y);
Point.origin()
: x = 0,
y = 0;
}
final myPoint = Point.origin();
Factory constructor可以讓你不必要創立新的類別instance,如果你將類別的instance保存在記憶體中並且不想每次都創建一個新instance,那Factory constructor非常方便,且Factory constructors可以回傳subtypes或是null值
class Square extends Shape {}
class Circle extends Shape {}
class Shape {
Shape();
factory Shape.fromTypeName(String typeName) {
if (typeName == 'square') return Square();
if (typeName == 'circle') return Circle();
throw ArgumentError('Unrecognized $typeName');
}
}
參考資料:
https://dart.dev/codelabs/dart-cheatsheet
https://www.freecodecamp.org/news/constructors-in-dart/#:~:text=A%20factory%20constructor%20is%20a,creating%20an%20instance%20is%20costly).